# Makefile for yemu project
#
# Goal:       Build the executable 'build/yemu'
# Sources:    src/*.c
# Headers:    src/*.h, image/build/*.h
# Build dir:  build/
#
# This Makefile supports automatic dependency tracking and
# incremental builds. All .c files in src/ are compiled automatically.

# Compiler and flags
CC      = gcc
CFLAGS  = -Wall -Wextra -O3 -I./src -I./image/build  # Enable warnings, optimizations, set include paths
LDFLAGS =

# Directory variables
SRC_DIR   = src
BUILD_DIR = build

# Source and object files
SRCS  := $(wildcard $(SRC_DIR)/*.c)  # All .c files in src/
OBJS  := $(patsubst $(SRC_DIR)/%.c, $(BUILD_DIR)/%.o, $(SRCS))  # Corresponding .o files in build/
DEPS  := $(OBJS:.o=.d)  # Dependency files generated by -MMD

# Target executable
TARGET := $(BUILD_DIR)/yemu

.PHONY: all clean

# Default target: build the executable
all: $(TARGET)

# Link all object files to create the final executable
$(BUILD_DIR)/yemu: $(OBJS)
	$(CC) $(LDFLAGS) -o $@ $^

# Compile each .c file to .o, generate dependency files (.d)
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c | $(BUILD_DIR)
	$(CC) $(CFLAGS) -MMD -MP -c $< -o $@

# Ensure build directory exists before compiling
$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

# Clean all build artifacts (object, dependency, and binary files)
clean:
	rm -rf $(BUILD_DIR)

# Automatically include dependency files, so changes to headers trigger rebuilds
# If no .d files exist, this line does nothing (safe on first build)
-include $(DEPS)